<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="30%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="部门编码" prop="dept_code">
        <ElInput v-model="formData.dept_code" placeholder="请输入部门编码" />
      </ElFormItem>
      <ElFormItem label="部门名称" prop="dept_name">
        <ElInput v-model="formData.dept_name" placeholder="请输入部门名称" />
      </ElFormItem>
      <ElFormItem label="上级部门" prop="parent_code">
        <ElSelect v-model="formData.parent_code" placeholder="请选择上级部门编号" :filterable="true" :clearable="true">
          <ElOption v-for="op in departments" :key="op.dept_code" :value="op.dept_code" :label="op.dept_name" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="主管" prop="manager_id">
        <ElSelect v-model="formData.manager_id" placeholder="请选择主管" :filterable="true" :clearable="true">
          <ElOption v-for="s in salers" :key="s.id" :value="s.id" :label="s.name" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="状态" prop="status">
        <ElSelect v-model="formData.status" :clearable="true" placeholder="请选择状态">
          <ElOption :value="true" label="启用" />
          <ElOption :value="false" label="禁用" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="描述" prop="descriptions">
        <ElInput v-model="formData.descriptions" type="textarea" placeholder="请输入描述" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-ripple>提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createDept, updateDept, type DeptResponse } from '@/api/system/dept'
import { useSystemStore } from '@/store/modules/system'

const system = useSystemStore()
const departments = computed(() => system.getDepartments)
const salers = computed(() => (system.getSalers || []).filter((s) => s.is_supervisor === 'Y'))

onMounted(async () => {
  await system.init(['departments', 'salers'])
})

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: Partial<DeptResponse>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '添加部门' : '编辑部门'))

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  dept_name: '',
  dept_code: '',
  parent_code: '',
  descriptions: '',
  manager_id: '',
  manager_name: '',
  status: true
})

// 校验规则
const rules: FormRules = {
  dept_name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  dept_code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }]
}

// 初始化表单
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.editData
  const row = props.editData || {}
  Object.assign(formData, {
    dept_name: isEdit ? (row.dept_name || '') : '',
    dept_code: isEdit ? (row.dept_code || '') : '',
    manager_id: isEdit ? (String(row.manager_id || '')) : '',
    manager_name: isEdit ? (row.manager_name || '') : '',
    parent_code: isEdit ? (row.parent_code || '') : '',
    descriptions: isEdit ? (row.descriptions || '') : '',
    status: isEdit ? Boolean(row.status) : true
  })
}

watch(
  () => [props.visible, props.type, props.editData],
  async ([visible]) => {
    if (visible) {
      initFormData()
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: true }
)

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    // 根据当前选择的 manager_id 从全量业务员中查找名称，作为提交用的 manager_name
    const selected = (system.getSalers || []).find((s: any) => String(s.id) === String(formData.manager_id))
    const resolvedManagerName = selected?.name || props.editData?.manager_name || ''
    const payload = {
      dept_name: formData.dept_name,
      dept_code: formData.dept_code,
      parent_code: formData.parent_code,
      manager_id: Number(formData.manager_id),
      manager_name: resolvedManagerName || null,
      descriptions: formData.descriptions || null,
      status: Boolean(formData.status)
    }

    try {
      if (props.type === 'add') {
        await createDept(payload)
      } else {
        const id = Number(props.editData?.id)
        if (!id) {
          ElMessage.error('缺少部门ID，无法编辑')
          return
        }
        await updateDept(id, payload)
      }

      // 更新system store中的部门缓存数据
      if (props.type === 'edit') {
        // 编辑模式：更新缓存中的部门信息
        const updatedDept = {
          dept_code: payload.dept_code,
          dept_name: payload.dept_name
        }
        system.mergeData({
          departments: system.getDepartments.map(dept =>
            dept.dept_code === payload.dept_code ? updatedDept : dept
          )
        })
      } else {
        // 新增模式：重新加载部门数据以包含新部门
        system.init(['departments'], { force: true })
      }

      ElMessage.success('提交成功')
      emit('submit')
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>